//
//  WBUserAccount.swift
//  Weibo
//
//  Created by wade on 17/3/6.
//  Copyright © 2017年 wade. All rights reserved.
//

import UIKit

private let accountFile : NSString = "useraccount.json"

class WBUserAccount: NSObject {

    var access_token:String?// = "2.00CDxNMB5_cVCEcf68fcfafe07MBvm"
    
    var uid:String?
    
    var expires_in: TimeInterval = 0 {
        
        didSet{expiresDate = Date(timeIntervalSinceNow: expires_in)}
        
    }
    
    var expiresDate : Date?
    
    var remind_in:TimeInterval = 0.0
    
    var screen_name : String?
    
    var avatar_large : String?
    
    
    override var description: String{
    
        return yy_modelDescription()
    
    }
    
    override init() {
        super.init()
        
        
        guard let path = accountFile.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:Any]
            else {
            return
        }
        
        yy_modelSet(with: dict ?? [:])
        
        //测试过期日期
        //expiresDate = Date(timeIntervalSinceNow:  -3600 * 24)
        
        if expiresDate?.compare(Date()) != .orderedDescending{
        
            print("账户过期")
            
            access_token = nil
            uid = nil
            
            _ = try? FileManager.default.removeItem(atPath: path)
        
        }
        
    }
    
    
    
    func saveAccount() {
    
        var dict = self.yy_modelToJSONObject() as? [String:Any] ?? [:]

        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accountFile.cz_appendDocumentDir() else {
        
            return
        
        }
        (data as NSData).write(toFile: filePath, atomically: true)
        
        
        print("用户信息保存成功 \(filePath)")
        
    }
    
}
